<script setup lang="ts">
import { ColumnsType } from 'ant-design-vue/es/table';
import { h } from 'vue'
const antIcons: any = inject('antIcons')
import { GetUserPageRes, getUserPage, adminUpdate, AdminUpdateRes, registerUserApi, RegisterRes } from '@/api/security'
import { SysUser, RegisterParams } from '@/interface/user';
import { deleteUser } from '@/api/security'
import { message } from 'ant-design-vue';
import {
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons-vue'
import { Key } from 'ant-design-vue/es/table/interface';
import { useGlobalStore } from '@/store/globalStore';

const columns: ColumnsType<any> = [
  {
    title: '名称',
    dataIndex: 'nickName',
    key: 'nickName',
    ellipsis: true,
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    ellipsis: true,
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
    width: 60,
  },
  {
    title: '电话号码',
    dataIndex: 'phonenumber',
    key: 'phonenumber',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '登陆日期',
    dataIndex: 'loginDate',
    key: 'loginDate',
    ellipsis: true,
  },
  {
    title: '登陆IP',
    dataIndex: 'loginIp',
    key: 'loginIp',
    ellipsis: true,
  },
  {
    title: '创建者',
    dataIndex: 'createBy',
    key: 'createBy',
    ellipsis: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    ellipsis: true,
  },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: 150,
  },
];

const globalStore = useGlobalStore()

const data = ref<SysUser[]>([])

const contentBoxRef = ref<HTMLElement>()
const currentPage = ref<number>(1);
const size = ref<number>(10);
const total = ref<number>(0);
const isLoading = ref<boolean>(false);
const editApiLoading = ref<boolean>(false);
const editPopShow = ref<boolean>(false);
const searchValue = ref('')

const currEditData = reactive<SysUser>({
  userId: -1,
  nickName: '',
  userName: '',
  sex: '',
  phonenumber: '',
  email: '',
  status: '',
  remark: ''
})

const tableStyle = reactive<{
  width: number,
  height: number
}>({
  width: 300,
  height: 300
})

const getUsers = async (isSearch = false) => {
  isLoading.value = true;
  data.value = []
  if (isSearch) {
    pageChanged(1, size.value)
    return
  }
  try {
    const { data: res }: { data: GetUserPageRes<any> } = await getUserPage(currentPage.value, size.value, searchValue.value)
    currentPage.value = res.data.current
    size.value = res.data.size
    total.value = res.data.total
    //key用于选中操作
    data.value = res.data.records.map((item: any) => {
      item.key = item.userId
      return item
    })
  } catch (error) {

  } finally {
    isLoading.value = false;
  }
}

const pageChanged = (page: number, pageSize: number) => {
  currentPage.value = page
  size.value = pageSize
  getUsers()
}

const reloadData = () => {
  getUsers()
}

const resetData = () => {
  searchValue.value = ''
  pageChanged(1, 10)
}

const deleteData = async (_e: MouseEvent, userId: number) => {
  return new Promise((resolve) => {
    deleteUser(userId.toString()).then(res => {
      if (res.data.code == 200) {
        message.success('删除成功')
        reloadData()
      } else {
        message.error(res.data.msg || '删除失败')
      }
      resolve(true)
    })
  });
}

const deleteBatchData = async () => {
  deleteUser(selectedRows.value.join(',')).then(res => {
    if (res.data.code == 200) {
      message.success('删除成功')
    } else {
      message.error(res.data.msg || '删除失败')
    }
    getUsers()
  })
}

const toggleDataStatus = (_checked: boolean | string | number, _event: Event) => {

}

const handleEditOk = async () => {
  editApiLoading.value = true
  try {
    const { data: res }: { data: AdminUpdateRes } = await adminUpdate(currEditData)
    if (res.code == 200) {
      message.success('更新成功')
      getUsers()
      editPopShow.value = false
    } else {
      message.error(res.msg || '更新失败')
    }
  } catch (error) {

  } finally {
    editApiLoading.value = false
  }
}

const editData = (sysUser: any) => {
  editPopShow.value = true
  const { nickName, userName, sex, phonenumber, email, status, remark, userId } = sysUser
  currEditData.userId = userId
  currEditData.nickName = nickName
  currEditData.userName = userName
  currEditData.sex = sex
  currEditData.phonenumber = phonenumber
  currEditData.email = email
  currEditData.status = status
  currEditData.remark = remark
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

//当前选中行
const selectedRows = ref<Key[]>([])
const onSelectChange = (selectedRowKeys: Key[]) => {
  selectedRows.value = selectedRowKeys;
};

//注册模块
const currAddData = ref<RegisterParams>({
  username: '',
  password: '',
  captchaCode: '',
  uuidKey: ''
})

const addPopShow = ref(false)
const addApiLoading = ref(false)

const handleAddOk = async () => {
  try {
    addApiLoading.value = true
    const { data: res }: { data: RegisterRes } = await registerUserApi(currAddData.value)
    if (res.code === 200) {
      message.success('注册成功')
      getUsers()
      addPopShow.value = false
      currAddData.value.username = ''
      currAddData.value.password = ''
    } else {
      message.error(res.msg || '注册失败')
    }
  } catch (error) {

  } finally {
    addApiLoading.value = false
  }
}

const onAddFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

const handleAddData = () => {
  addPopShow.value = true
}

onMounted(() => {
  getUsers()
  tableStyle.height = contentBoxRef.value?.clientHeight as number - 200
  tableStyle.width = contentBoxRef.value?.clientWidth as number
})
</script>
<template>
  <div class="box-border relative h-full p-3" ref="contentBoxRef"
    :style="{ width: globalStore.isMobile ? 'calc(100% - 60px)' : '100%' }">
    <a-row>
      <a-col :span="24">
        <a-space class="flex flex-wrap">
          <a-button type="ghost"
            class="flex items-center text-white bg-green-500 hover:bg-green-400 hover:border-green-400 "
            :icon="h(antIcons['PlusOutlined'])" @click="handleAddData" :loading="isLoading">新增</a-button>
          <a-input placeholder="名称/用户名/性别/电话号码" class="w-[230px]" v-model:value="searchValue"
            @keydown.enter="getUsers(true)" />
          <a-button type="primary" class="flex items-center bg-primary-2" :icon="h(antIcons['SearchOutlined'])"
            @click="getUsers(true)" :loading="isLoading">查询</a-button>
          <a-button class="flex items-center" :icon="h(antIcons['ReloadOutlined'])" @click="resetData">重置</a-button>
          <a-button class="flex items-center justify-center" :icon="h(antIcons['ReloadOutlined'])" shape="circle"
            @click="reloadData"></a-button>
          <a-button type="primary" class="flex items-center" danger :icon="h(antIcons['CloseOutlined'])"
            :disabled="selectedRows.length == 0" @click="deleteBatchData">删除</a-button>
        </a-space>
      </a-col>
    </a-row>
    <!-- 表格 -->
    <div class="mt-3 h-fit">
      <a-table :columns="columns" :data-source="data" :pagination="false" :loading="isLoading"
        :scroll="{ y: tableStyle.height, x: globalStore.isMobile ? 'calc(100% + 800px)' : '100%' }"
        :row-selection="{ selectedRowKeys: selectedRows, onChange: onSelectChange }">
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'sex'">
            <p>{{ text == '1' ? '男' : '女' }}</p>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-switch :checked="text === '0'" @click="toggleDataStatus" disabled>
              <template #checkedChildren>
                <CheckOutlined />
              </template>
              <template #unCheckedChildren>
                <CloseOutlined />
              </template>
            </a-switch>
          </template>
          <template v-if="column.key === 'operation'">
            <a-space>
              <a-button type="primary" class="flex items-center bg-primary-2" size="small"
                @click="editData(text)">编辑</a-button>
              <a-popconfirm :title="`确定删除${text.userName}吗?`" ok-text="确认" cancel-text="取消"
                :okButtonProps="{ type: 'default' }" @confirm="deleteData($event, text.userId)">
                <!-- <template #okButton>
                  <a-button size="small" type="primary" class="bg-primary-2" @click="deleteData(text.userId)">确认</a-button>
                </template> -->
                <a-button size="small" type="primary" danger class="flex items-center text-white ">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 p-3 mt-3 bg-white border-t-[1px] z-10 dark:bg-darkBg dark:border-gray-600">
      <a-pagination v-model:current="currentPage" v-model:page-size="size" :total="total"
        :show-total="total => `总共 ${total} 条`" show-size-changer @change="pageChanged" />
    </div>

    <a-modal v-model:open="editPopShow" title="修改用户信息" :footer="null">
      <a-form :model="currEditData" name="currEditData" @finish="handleEditOk" class="mt-5" place="left"
        @finishFailed="onFinishFailed" v-bind="{
      labelCol: { span: 4 },
      wrapperCol: { span: 24 },
    }">
        <a-form-item name="nickName" label="名称" :rules="[{ required: true }]">
          <a-input v-model:value="currEditData.nickName" />
        </a-form-item>
        <a-form-item name="userName" label="用户名" :rules="[{ required: true }]">
          <a-input v-model:value="currEditData.userName" />
        </a-form-item>
        <a-form-item name="sex" label="性别" :rules="[{ required: false }]">
          <a-select ref="select" v-model:value="currEditData.sex" style="width: 120px">
            <a-select-option value="1">男</a-select-option>
            <a-select-option value="0">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item name=".phonenumber" label="电话号码" :rules="[{ required: false }]">
          <a-input v-model:value="currEditData.phonenumber" />
        </a-form-item>
        <a-form-item name="email" label="邮箱" :rules="[{ required: false }]">
          <a-input v-model:value="currEditData.email" />
        </a-form-item>
        <a-form-item name="status" label="状态" :rules="[{ required: false }]">
          <a-switch v-model:checked="currEditData.status" checkedValue="0" unCheckedValue="1">
            <template #checkedChildren>
              <CheckOutlined />
            </template>
            <template #unCheckedChildren>
              <CloseOutlined />
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item name="remark" label="备注" :rules="[{ required: false }]">
          <a-input v-model:value="currEditData.remark" />
        </a-form-item>
        <a-form-item :wrapper-col="{
      offset: 17,
      span: 7
    }">
          <a-space>
            <a-button key="back" @click="editPopShow = false">取消</a-button>
            <a-button html-type="submit" type="primary" class="bg-primary-2" :loading="editApiLoading">修改</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="addPopShow" title="注册用户" :footer="null">
      <a-form :model="currAddData" name="currAddData" @finish="handleAddOk" class="mt-5" place="left"
        @finishFailed="onAddFinishFailed" v-bind="{
      labelCol: { span: 4 },
      wrapperCol: { span: 24 },
    }">
        <a-form-item name="username" label="用户名" :rules="[{ required: true }]">
          <a-input v-model:value="currAddData.username" placeholder="用户名" />
        </a-form-item>
        <a-form-item name="password" label="密码" :rules="[{ required: true }]">
          <a-input v-model:value="currAddData.password" placeholder="密码" />
        </a-form-item>
        <a-form-item :wrapper-col="{
      offset: 17,
      span: 7
    }">
          <a-space>
            <a-button key="back" @click="addPopShow = false">取消</a-button>
            <a-button html-type="submit" type="primary" class="bg-primary-2" :loading="addApiLoading">注册</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>